package com.example.estest.util;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 日志信息匹配规则，提取关键信息
 */
public class LogParser {

    public static void func(Map<String, Object> logData,String logMessage,String logpath) {
        //logMessage = "2023-11-13 15:42:31 [24315]:auth_type:[pop],extra_type:[],acct_id:[498483],domain_id:[496704],acct_type:[0],domain_type:[0].acct_name:[yuanren],real_acc_name:[yuanren],domain_name:[sgcc.com.cn].real_domain_name:[sgcc.com.cn],admin_type:[0],client_ip:[122.10.141.107],server_name:[localhost],reasult:[Auth Success]";

        // 定义 Grok 模式的正则表达式
        String grokPattern = "(?<time>\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}).*auth_type:\\[(?<mailprotocol>[^\\]]+)\\].*acct_name:\\[(?<acctNames>[^\\]]+)\\].*domain_name:\\[(?<domainName>[^\\]]+)\\].*client_ip:\\[(?<clientIP>[^\\]]+)\\].*server_name:\\[(?<serverName>[^\\]]+)\\].*reault:\\[(?<result>[^\\]]+)\\]";


        // 编译正则表达式
        Pattern pattern = Pattern.compile(grokPattern);

        // 匹配日志消息
        Matcher matcher = pattern.matcher(logMessage);

        // 提取字段
        if (matcher.matches()) {
            String mailProtocol = matcher.group("mailprotocol");
            String acctNames = matcher.group("acctNames");
            String domainName = matcher.group("domainName");
            String clientIP = matcher.group("clientIP");
            String serverName = matcher.group("serverName");
            String result = matcher.group("result");

            String time = matcher.group("time");
            String[] split = time.split("\\+");
            String time1 = split[0];
            if(time1.contains("T")) {
                String[] split1 = time1.split("T");
                time = split1[0]+split1[1];
            } else {
                time = time1;
            }

            if(mailProtocol.contains("web")) {
                mailProtocol = "web";
            }
            logData.put("mail_name",acctNames);
            logData.put("mail_domain",domainName);
            logData.put("domainName",domainName);
            logData.put("mail_protocol",mailProtocol);
            logData.put("acctNames",acctNames);
            logData.put("clientIP",clientIP);
            logData.put("serverName",serverName);
            logData.put("result",result);
            logData.put("mail",acctNames+"@"+domainName);
        } else {
            FileUtils.writeStringadd(logpath+"\\"+"error.log", DateUtil.getData()+"------"+logMessage+"----Log message does not match the pattern.");
        }
    }

}


